package com.kwt.course;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class TankFrame extends Frame {
    Tank myTank = new Tank(200, 200, Dir.down);


    public TankFrame() {
        setSize(800, 500);
        setResizable(false);
        setTitle("tank");
        setVisible(true);
        addKeyListener(new MyKeyListener());

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }


    /**
     * 移动的方法
     *
     * @param g
     */
    @Override
    public void paint(Graphics g) {
        myTank.paint(g);
    }


    /**
     * 键盘监听处理类
     */

    class MyKeyListener extends KeyAdapter {
        /**
         *
         */
        boolean bL = false;
        boolean bU = false;
        boolean bR = false;
        boolean bD = false;

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            switch (keyCode) {
                case KeyEvent.VK_LEFT:
                    bL = true;
                    break;
                case KeyEvent.VK_UP:
                    bU = true;
                    break;
                case KeyEvent.VK_RIGHT:
                    bR = true;
                    break;
                case KeyEvent.VK_DOWN:
                    bD = true;
                    break;
                default:
                    break;
            }
            setMainTankDir();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            int keyCode = e.getKeyCode();
            switch (keyCode) {
                case KeyEvent.VK_LEFT:
                    bL = false;
                    break;
                case KeyEvent.VK_UP:
                    bU = false;
                    break;
                case KeyEvent.VK_RIGHT:
                    bR = false;
                    break;
                case KeyEvent.VK_DOWN:
                    bD = false;
                    break;
                default:
                    break;
            }
            setMainTankDir();
        }

        private void setMainTankDir() {
            if (bL) myTank.setDir(Dir.left);
            if (bU) myTank.setDir(Dir.up);
            if (bR) myTank.setDir(Dir.right);
            if (bD) myTank.setDir(Dir.down);
        }
    }
}
